<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\analysis\material;

use app\command\BaseWork;
use app\model\mongo\MongoInfoModel;
use app\service\analysis\data\info\SystemMaterialService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

class MaterialSystemWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('analysis_material_system_work');
        // 设置参数
        $this->setDescription('数据分析-系统素材打标')
            ->addArgument('media_id', Argument::REQUIRED, '媒体类型')
            ->addArgument('type', Argument::REQUIRED, '类型 2：视频  3：图片')
            ->setHelp('php think analysis_material_system_work [media_id] [type]');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $mediaId = intval($input->getArgument('media_id'));
        $type = intval($input->getArgument('type'));

        $obj = new SystemMaterialService($mediaId, $type);
        if (! $obj->isService()) {
            $this->getOutputMessage(SystemMaterialService::getError(0));
            return;
        }
        // 超过5min就停止
        $t = time();
        $runTime = 5 * 60;
        while (time() - $t <= $runTime) {
            try {
                $items = $obj->getList();
                if (count($items) == 0) {
                    $this->getOutputMessage('暂无数据睡眠中');
                    sleep(rand(5, 10));
                    continue;
                }
                foreach ($items as $model) {
                    if (! $model instanceof MongoInfoModel || ! $model->getKey()) {
                        $this->getOutputMessage('素材对象错误');
                        continue;
                    }

                    $this->getOutputMessage('打标[' . $model->getKey() . ']开始');
                    if (! $obj->runTask($model)) {
                        $this->getOutputMessage('打标[' . $model->getKey() . ']失败:' . $obj::getError(0));
                    }
                    $this->getOutputMessage('打标[' . $model->getKey() . ']完成');
                }
            } catch (\Exception $e) {
                $this->getOutputMessage('错误：' . $e->getMessage());
                echo $e->getLine() . PHP_EOL;
                echo $e->getFile() . PHP_EOL;
                echo $e->getTraceAsString() . PHP_EOL;
            }
        }
        $this->getOutputMessage('素材打标结束');
    }
}
